<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\Admin\Lib;

/**
 * Allows to record execution times of the application.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class Timer {

  /**
   * @var float Timestamp of the previous call.
   */
  protected $previous;

  /**
   * @var float Total execution time.
   */
  protected $total = .0;

  /**
   * @var array Recorded time.
   */
  protected $elapsed = array();

  /**
   * Logs the execution time after the last log operation, optionally
   * pre-pending a supplied text message.
   *
   * @param string $message
   */
  public function log($message = '') {
    if ($this->previous) {
      $current = microtime(true);
      $time = $current - $this->previous;
      $this->total += $time;
      if ($message) $message .= ': ';
      $this->elapsed[] = $message . number_format($time, 3) . 'sec';
      $this->previous = $current;
    } else {
      $this->previous = microtime(true);
    }
  }

  /**
   * Returns an array of logged times.
   *
   * @return array
   */
  public function getLogged() {
    return $this->elapsed;
  }

  /**
   * Returns the total execution time between the first and the last log
   * operation in seconds.
   *
   * @return float
   */
  public function getTotal() {
    return $this->total;
  }

  /**
   * Creates a string representation of the log.
   *
   * @return string
   */
  public function __toString() {
    return json_encode(array(
      'log' => $this->elapsed,
      'total' => $this->total,
    ));
  }

}